package com.tvmao.testplugin;

import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.tvmao.plugin.contract.Plugin;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import dalvik.system.DexClassLoader;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void loadPluginAndTest(View view) {
        loadPluginAndTest();
    }

    public void loadPluginAndTest() {
        Context appContext = this;
        String pluginPath = Environment.getExternalStorageDirectory() + File.separator + "plugin.jar.dex";

        File file = new File(pluginPath);

        File optimizedDirectoryFile = appContext.getDir("dex", 0);//不能SD card
        try {
            ClassLoader classLoader = appContext.getClassLoader();
            DexClassLoader localDexClassLoader = new DexClassLoader(pluginPath, optimizedDirectoryFile.getAbsolutePath(),
                    null, classLoader);
            //load class
            Class localClass = localDexClassLoader.loadClass("com.tvmao.plugin.test.TestPlugin");
            //construct instance
            Constructor localConstructor = localClass.getConstructor(new Class[]{});
            Object instance = localConstructor.newInstance(new Object[]{});
            //call method
            Plugin plugin = (Plugin) instance;
            plugin.test(appContext);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
